//
//  WmcPhotoPreviewToolView.swift
//  YPWatermarkCamera
//
//  Created by 马涛 on 2022/6/30.
//

import UIKit
import YPBedrock
import YPGraphicEngine

public extension WmcButtonItemType {
    enum PreviewFooter: Equatable {
        /// 重拍
        case retake

        /// 编辑
        case edit

        /// 水印
        case watermark

        /// 分享
        case shared

        /// 分享朋友圈
        case friendCircle

        /// 分享微信
        case wechat

        /// 占位
        case placeholder

        /// 自定义
        case custom(view: UIView)
    }

    /// 中间按钮
    enum PreviewCenter: Equatable {
        /// 默认按钮
        case `default`

        /// 无按钮
        case none

        /// 自定义
        case custom(view: UIView)
    }
}

// MARK: - [WmcPhotoPreviewFooterView]

class WmcPhotoPreviewFooterView: WmcBaseView {
    lazy var leftStackView: UIStackView = {
        let view = UIStackView()
        view.backgroundColor = UIColor.clear
        view.axis = .horizontal
        view.spacing = 0
        view.alignment = .fill
        view.distribution = .fillEqually
        return view
    }()

    lazy var rightStackView: UIStackView = {
        let view = UIStackView()
        view.backgroundColor = UIColor.clear
        view.axis = .horizontal
        view.spacing = 0
        view.alignment = .fill
        view.distribution = .fillEqually
        return view
    }()

    /// 保存按钮
    lazy var saveBtn: WmcPhotoPreviewSaveButton = {
        let view = WmcPhotoPreviewSaveButton()
        view.uploadImgView.image = "save_img_icon".wmc_image
        view.titleLabel.text = "存相册"
        view.layer.cornerRadius = centerBtnSize.width / 2
        return view
    }()
    
    /// 重新拍摄
    lazy var retakeBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "重拍", image: "retake_photo_icon".wmc_image)
        return btn
    }()

    /// 编辑
    lazy var editBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "编辑", image: "edit".wmc_image)
        return btn
    }()

    /// 水印
    lazy var watermarkBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "水印", image: "home_tool_watermark".wmc_image)
        return btn
    }()

    /// 分享
    lazy var sharedBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "分享", image: "share".wmc_image)
        return btn
    }()

    /// 朋友圈
    lazy var friendCircleBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "朋友圈", image: "friends_circle_line".wmc_image)
        return btn
    }()

    /// 微信
    lazy var wechatBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "微信", image: "wechat_icon_line".wmc_image)
        return btn
    }()

    /// 中间按钮
    var centerView: UIView?

    /// 中心按钮大小
    let centerBtnSize: CGSize = .init(width: Wmc_screenWidth / 5, height: Wmc_screenWidth / 5)

    /// 背景是否透明状态
    var isTransparent: Bool = false

    /// 保存回调
    var saveBlock: YPBlock.Empty?
    
    /// 代理获取，减少代码长度
    var photoPreviewDelegate: WmcPhotoPreviewDelegate? {
        return YPWmcManager.shared.uiDelegate.photoPreviewDelegate
    }

    /// 工具栏所有按钮
    var toolBtns: [WmcTopImgBottomTextBtn] {
        return [retakeBtn, editBtn, watermarkBtn, sharedBtn, friendCircleBtn, wechatBtn]
    }

    /// 通用创建一种样式的按钮
    func createTopImgBottomTextBtn(title: String, image: UIImage) -> WmcTopImgBottomTextBtn {
        let btn = WmcTopImgBottomTextBtn(title: title, image: image)
        btn.font = 14.yp.uiFont(weight: .medium)
        btn.imgTextSpacing = 9
        btn.imgSize = 25
        return btn
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let superHit = super.hitTest(point, with: event)
        guard bounds.contains(point) else { return superHit }
        for view in subviews {
            if view.frame.contains(point) {
                if !(superHit is UIStackView) {
                    return superHit
                }
            }
        }
        return nil
    }

    override func makeUI() {
        addSubview(leftStackView)
        addSubview(rightStackView)

        leftStackView.snp.makeConstraints { make in
            make.centerY.equalToSuperview().offset(-10)
            make.left.equalToSuperview()
            make.right.equalTo(snp.centerX).offset(-centerBtnSize.width / 2)
            make.height.equalTo(55)
        }
        rightStackView.snp.makeConstraints { make in
            make.top.equalTo(leftStackView.snp.top)
            make.right.equalToSuperview()
            make.left.equalTo(snp.centerX).offset(centerBtnSize.width / 2)
            make.bottom.equalTo(leftStackView)
        }
        reloadItems()
    }

    override func bindViewAction() {
        saveBtn.yp.addEvent { [weak self] btn in
            
            let btnAction: () -> Void = {
                btn.isUserInteractionEnabled = false
                btn.playAnimation() { [weak self] in
                    guard let weakSelf = self else { return }
                    btn.isUserInteractionEnabled = true
                    weakSelf.saveBlock?()
                }
            }
            
            if WmcLoginManager.shared.isLogin {
                let syncSettingsView = WmcSyncSettingsView.showInView(style: .confirmType)
                syncSettingsView.ensureClosure = { list in
                    btnAction()
                }
                
                YPApp.CurrentVC?.view.addSubview(syncSettingsView)
                
                let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: syncSettingsView, contentLayoutBlock: { make in
                    make.left.right.bottom.equalToSuperview()
                    make.height.equalTo(373)
                }))
                presentVC.show()
            } else {
                btnAction()
            }
        }
    }
    
    /// 刷新按钮
    func reloadItems() {
        if isTransparent {
            backgroundColor = UIColor.black.yp.alpha(0.4)
        } else {
            backgroundColor = UIColor.white
        }
        toolBtns.forEach { btn in
            if isTransparent {
                btn.setTintColor(.white)
            } else {
                btn.setImageTintColor(.wmc_grayH2_323233)
                btn.textColor = .wmc_grayH8_8A8A99
            }
        }
        reloadLeftItems()
        reloadRightItems()
        reloadCenterItem()
    }

    /// 刷新左按钮
    func reloadLeftItems() {
        var defalultList: [WmcButtonItemType.PreviewFooter] = [
            .retake, .watermark,
        ]
        // 询问代理
        if let caseList = photoPreviewDelegate?.toolLeftMenuList(.current,
                                                                 isTransparent: isTransparent,
                                                                 defaultList: defalultList)
        {
            defalultList = caseList
        }

        let leftBtns = createItems(caseList: defalultList)
        leftStackView.yp.arrangedSubviews = leftBtns
    }

    /// 刷新右按钮
    func reloadRightItems() {
        var defalultList: [WmcButtonItemType.PreviewFooter] = [
            .friendCircle, .wechat,
        ]
        // 询问代理
        if let caseList = photoPreviewDelegate?.toolRightMenuList(.current,
                                                                  isTransparent: isTransparent,
                                                                  defaultList: defalultList)
        {
            defalultList = caseList
        }

        let leftBtns = createItems(caseList: defalultList)
        rightStackView.yp.arrangedSubviews = leftBtns
    }

    /// 刷新中间按钮
    func reloadCenterItem() {
        centerView?.removeFromSuperview()
        centerView = nil
        // 新建
        let centerBtn = createToolCenterBtn()
        addSubview(centerBtn)
        centerBtn.snp.makeConstraints { make in
            make.centerY.equalTo(leftStackView)
            make.centerX.equalToSuperview()
            make.size.equalTo(centerBtnSize)
        }
        centerView = centerBtn
    }

    /// 构建工具栏中间按钮
    func createToolCenterBtn() -> UIView {
        var defaultItem: WmcButtonItemType.PreviewCenter = .default
        // 询问代理
        if let _defaultItem = photoPreviewDelegate?.toolCenterMenuItem(.current,
                                                                       isTransparent: isTransparent,
                                                                       defaultItem: defaultItem)
        {
            defaultItem = _defaultItem
        }
        switch defaultItem {
        case .default:
            return saveBtn
        case .none:
            return UIView()
        case let .custom(view: view):
            return view
        }
    }

    /// 构建自定义菜单
    func createItems(caseList: [WmcButtonItemType.PreviewFooter]) -> [UIView] {
        var items: [UIView] = []
        caseList.forEach { type in
            switch type {
            case .retake: items.append(retakeBtn)
            case .edit: items.append(editBtn)
            case .watermark: items.append(watermarkBtn)
            case .shared: items.append(sharedBtn)
            case .friendCircle: items.append(friendCircleBtn)
            case .wechat: items.append( wechatBtn)
            case .placeholder: items.append(UIView())
            case let .custom(view: customView): items.append(customView)
            }
        }
        return items
    }
}
